package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.UserLocation;
import com.itheima.service.mongo.UserLocationService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UserLocationServiceImpl implements UserLocationService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveLocation(Double longitude, Double latitude, String addrStr, Long userId) {
       //1. 先查
        UserLocation userLocation = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)),
                UserLocation.class);
        //2.判断
        if(userLocation==null){ //新增
            userLocation = new UserLocation();
            userLocation.setUserId(userId); //用户id
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude)); //地图坐标经纬度
            userLocation.setAddress(addrStr); //地址描述
            userLocation.setCreated(System.currentTimeMillis()); //上报时间
            userLocation.setUserId(System.currentTimeMillis()); //更新时间
        }else { //更新
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude)); //地图坐标经纬度
            userLocation.setAddress(addrStr); //地址描述
            userLocation.setUserId(System.currentTimeMillis()); //更新时间

        }
        //调用mongo
        mongoTemplate.save(userLocation);
    }

    @Override
    public List<Long> searchNearUser(Long userId, Long distance) {
        //1. 找圆心
        GeoJsonPoint location = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)),
                UserLocation.class).getLocation();
        //2.指定半径
        Distance dis = new Distance(distance / 1000, Metrics.KILOMETERS);
        //3. 画圆
        Circle circle = new Circle(location, dis);
        //4. 条件搜素
        Query query = new Query(Criteria.where("localtion").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(query, UserLocation.class);
        //5. 遍历返回id
        ArrayList<Long> nearUserIdList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(userLocationList)){
            for (UserLocation userLocation : userLocationList) {
                nearUserIdList.add(userLocation.getUserId());
            }
        }
        return nearUserIdList;
    }
}
